package com.uam.core.lk.utils;

import com.alibaba.fastjson.JSONObject;
import com.uam.core.lk.utils.enums.FeiShuOperationEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 * 飞书发送飞书群对象
 *
 * @author heguanglong
 * @date 2022/5/18
 */
@Slf4j
public class FeiShuUtil {

    public static String sendFeiShuMsg(String url, String token, FeiShuOperationEnum msg, String error,String env) {
        String hostName = null;
        String localIp = null;
        try {
            InetAddress address = InetAddress.getLocalHost();
            hostName = address.getHostName();
            localIp = address.getHostAddress();
        } catch (UnknownHostException e) {

        }

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", msg.getStatus());
            jsonObject.put("title", msg.getLabel());
            List<String> jsonArray = new ArrayList<>(3);
            jsonArray.add("服务名称：" + msg.getName());

            if(StringUtils.isNotBlank(env)){
                jsonArray.add("环境：" + env);
            }

            if (StringUtils.isNotBlank(hostName)) {
                jsonArray.add("主机名：" + hostName);
            }

            if (StringUtils.isNotBlank(localIp)) {
                jsonArray.add("ip地址:" + localIp);
            }
            jsonArray.add("消息:" + msg.getMsg());

            if (StringUtils.isNotBlank(error)) {
                jsonArray.add(error);
            }
            jsonObject.put("data", jsonArray);
            String data = jsonObject.toJSONString();
            return HttpClientUtils.postToken(url, token, data);
        } catch (Exception e) {
            log.error("发送飞书消息错误", e);
        }
        return null;
    }

    public static String sendFeiShuMsg(String url, String token, FeiShuOperationEnum msg) {
        return sendFeiShuMsg(url,token,msg,null,null);
    }

    public static String sendFeiShuMsg(String url, String token, FeiShuOperationEnum msg,String error) {
        return sendFeiShuMsg(url,token,msg,error,null);
    }
}
